<template>
  <div class="call-label" id="callTable">
    <div id="call_cont" style="padding: 0 20px 40px;">
      <div class="title" :title="$t('channelsettings.callLabel0')">
        {{$t('channelsettings.callLabel0')}}
      </div>
      <div class="operate-div">
        <div class="left">
          <span @click.stop="add" class="add"><i class="el-icon-plus"></i>{{$t('config.channel.addOneLabel')}}</span>
          <span @click.stop="refresh" style="padding-right: 10px; cursor: pointer"><i class="iconfont icon-shuaxin"></i>{{$t('public.refresh')}}</span>
          <span @click.stop="importLabel" style="padding-right: 10px; cursor: pointer"><i class="icon iconfont icon-daoru"></i>{{$t('config.customer.import')}}</span>
          <span @click.stop="exoprtLabel" style="padding-right: 10px; cursor: pointer"><i class="icon iconfont icon-daochu1"></i>{{$t('public.export')}}</span>
        </div>
        <el-input
          :placeholder="$t('config.channel.inpputWar')"
          class="condition right"
          v-model="searchContent"
          size="mini"
          @keyup.native.enter="handleIconClick"
        >
          <i
            class="el-input__icon el-icon-search"
            slot="suffix"
            @click="handleIconClick">
          </i>
        </el-input>
        <span class="state">{{$t('public.state')}}：</span>
        <el-select v-model="filterEnable" :placeholder="$t('public.pleasePick')">
          <el-option
            v-for="item in filterEnableList"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
        <el-button type="primary" class="primary_btn" size="small" @click="saveLabel()" style="margin-left:auto;">{{$t('public.save')}}</el-button>
      </div>
      <call-label-tree ref="tree" v-if="tableLoading" :tableData="tableData" :vagueStr = 'searchContent' @emptyStr = 'emptyStr' @filterEnableUpdate = 'filterEnableUpdate' @refreshData = "refreshData" :filterEnable = 'filterEnable'></call-label-tree>
      <el-dialog :close-on-click-modal="false" modal-append-to-body lock-scroll title="导入通话标签" :visible.sync="importLabelDialog" width="50%">
        <div class="btn-wrap">
          <el-button type="info" class="temp-download primary_btn">
            <a href="/static/template/label_template.xlsx" download>{{$t('km.downloadImport')}}</a>
          </el-button>
          <!--饿了么上传组件-->
          <el-upload
            class="temp-upload"
            :action="uploadUrl"
            accept=".xls,.xlsx"
            name="upload"
            :data="uploadHeaders"
            :with-credentials="true"
            :on-success="handleSuccess"
            :on-error="handleError"
            :before-upload="beforeUpload"
            :show-file-list="false">
            <el-button class="primary_btn" type="primary">{{$t('km.importName')}}</el-button>
          </el-upload>
        </div>
        <div class="import" v-show="importShow">
          <el-row :gutter="20">
            <el-col :span="4" class="label">{{$t('km.batchNo')}}</el-col>
            <el-col :span="10"><el-input v-model.trim="importObj.batchNo" :disabled="true"></el-input></el-col>
            <el-col :span="10"><el-input v-model.trim="importObj.batchRemark" @click.enter="importExcel" :placeholder="$t('km.batchNoMark')"></el-input></el-col>
          </el-row>
          <el-button class="primary_btn margin-t" @click.stop="importExcel" type="primary">{{$t("config.customer.import")}}</el-button>
        </div>
        <div class="instructions" v-html="$t('km.importTips2')" v-once></div>
      </el-dialog>
    </div>
  </div>
</template>
<script>
  import {getDateNo} from '@/utils/m7Utils'
  import callLabelTree from '@/components/business-modules/config/channelConfig/base/callLabelTree.vue'
  import * as XlsxUtil from 'src/utils/XlsxUtil.umd.js'
  export default {
    name: 'callLabel',
    data () {
      return {
        tableLoading: true,
        tableData: [],
        importLabelDialog: false,
        importShow: false,
        uploadUrl: '/fileUpload',
        allLabelList: [],
        exportLabelList: [],
        exportHeaders: [
          {name: "一级标签", prop: "multilabel1",width: 9},
          {name: "二级标签", prop: "multilabel2",width: 9},
          {name: "三级标签", prop: "multilabel3",width: 9},
          {name: "四级标签", prop: "multilabel4",width: 9},
          {name: "五级标签", prop: "multilabel5",width: 9}
        ],
        uploadHeaders: {
          type: 'undefined',
          module: '',
          sessionId: this.$store.state.session.sessionId
        },
        // 导入请求参数
        importObj: {
          batchNo: '',
          batchRemark: ''
        },
        fileObj: {
          filePath: '',
          fileName: ''
        },
        searchLabelName: '',
        searchContent: '',
        filterEnable: 'open',
        filterEnableList: [
          {
            label: this.$t('public.all'),
            value: 'all'
          },
          {
            label: this.$t('sms.reuse'),
            value: 'open'
          },
          {
            label: this.$t('sms.stop'),
            value: 'close'
          }
        ]
      }
    },
    methods: {
      // 上传前 配置上传参数
      beforeUpload (file) {
        this.uploadHeaders.key = 'file'
        this.uploadHeaders.name = file.name
        let arr = file.name.split('.')
        let arrType = ['xls', 'xlsx']
        if (arrType.indexOf(arr[arr.length - 1]) !== -1) {
          return true
        } else {
          this.$message.error(this.$t('km.fileTypeError'))
          return false
        }
      },
      //      上传成功
      handleSuccess (response) {
        if (response.success) {
          this.importObj.batchNo = getDateNo()
          this.importObj.batchRemark = ''
          this.importObj.fileName = response.filePath ? response.filePath.substring(response.filePath.lastIndexOf('/') + 1) : ''
          this.importObj.trueName = response.fileName || ''
          this.importShow = true
        } else {
          this.$message.error(this.$t('message.default_tips'))
        }
      },
      //      失败
      handleError () {
        this.$message.error(this.$t('message.default_tips'))
      },
      // 导入请求
      importExcel () {
        this.$store.dispatch('importCallLabel', this.importObj).then((resp) => {
          if (resp.success) {
            this.$message.success(this.$t('channelsettings.callLabel12'))
            this.importShow = false
            this.importLabelDialog = false
            setTimeout(() => { // 延时一下，导入异步
              this.refreshData()
            }, 400)
          }
        })
      },
      filterEnableUpdate (state) {
        this.filterEnable = state
      },
      emptyStr () {
        this.searchContent = ''
      },
      refreshData () {
        this.refresh()
      },
      saveLabel () {
        this.$refs.tree.handlesaveTreeLabel()
      },
      handleIconClick () {
        this.$refs.tree.forceUpdate()
      },
      add () {
        this.$refs.tree.handleAddLabeltest()
      },
      refresh () {
        this.searchContent = ''
        this.filterEnable = 'open'
        this.tableData = []
        this.fetchData()
      },
      importLabel () {
        this.importObj = {batchNo: '', batchRemark: ''}
        this.importShow = false
        this.importLabelDialog = true
      },
      exoprtLabel () {
        this.exportLabelList = []
        this.handleAllLabel(this.allLabelList, {}) 
        console.log(this.exportLabelList, '=======')
        var dh = XlsxUtil.getDownloadHelper(this.exportHeaders, this.exportLabelList)
        var timeStamp = XlsxUtil.dateFormat(new Date(), 'yyyy-MM-dd hh-mm-ss')
        dh.download('通话标签' + timeStamp)
      },
      handleAllLabel (data, parentTempObj) {
        data.forEach(item => {
          // if (item.child && item.child.length > 0) {
          //   debugger
          //   const temObj = parentTempObj
          //   temObj['multilabel'+ item.level] = item.name
          //   this.handleAllLabel(item.child, temObj)
          // } else {
          //   const temObj = parentTempObj
          //   temObj['multilabel'+ item.level] = item.name
          //   this.exportLabelList.push(temObj)
          // }
          const one = item.child
          if (one && one.length > 0) {
            one.forEach(item2 => {
              console.log(item2, '====')
              const two = item2.child
              if (two && two.length > 0) {
                two.forEach(item3 => {
                  const three = item3.child
                  if (three && three.length > 0) {
                    three.forEach(item4 => {
                      const four = item4.child
                      if (four && four.length > 0) {
                        four.forEach(item5 => {
                          const tempObj = {}
                          tempObj['multilabel'+ item.level] = item.name
                          tempObj['multilabel'+ item2.level] = item2.name
                          tempObj['multilabel'+ item3.level] = item3.name
                          tempObj['multilabel'+ item4.level] = item4.name
                          tempObj['multilabel'+ item5.level] = item5.name
                          this.exportLabelList.push(tempObj)
                        })
                      } else {
                        const tempObj = {}
                        tempObj['multilabel'+ item.level] = item.name
                        tempObj['multilabel'+ item2.level] = item2.name
                        tempObj['multilabel'+ item3.level] = item3.name
                        tempObj['multilabel'+ item4.level] = item4.name
                        this.exportLabelList.push(tempObj)
                      }
                    })
                  } else {
                    const tempObj = {}
                    tempObj['multilabel'+ item.level] = item.name
                    tempObj['multilabel'+ item2.level] = item2.name
                    tempObj['multilabel'+ item3.level] = item3.name
                    this.exportLabelList.push(tempObj)
                  }
                })
              } else {
                const tempObj = {}
                tempObj['multilabel'+ item.level] = item.name
                tempObj['multilabel'+ item2.level] = item2.name
                this.exportLabelList.push(tempObj)
              }
            })
          } else {
            const tempObj = {}
            tempObj['multilabel'+ item.level] = item.name
            this.exportLabelList.push(tempObj)
          }
        })
      },
      confirmImport () {

      },
      fetchData () {
        this.tableLoading = false
        this.$store.dispatch('queryMultiCallLabels', {idle: ''}).then((resp) => {
          if (resp.list) {
            this.allLabelList = resp.list || []
            this.tableData = resp.list.sort(this.keysrt('enable',false))
            this.tableLoading = true
          }
        })
      },
      keysrt(key,desc) {
        return function(a,b){
          return desc ? ~~(a[key] < b[key]) : ~~(a[key] > b[key]);
        }
      },
      handleLabel (data) {
//        flag 控制展开收起    status 控制显示的是input  还是span
        for (let i = 0; i < data.length; i++) {
          var obj = {
            child: [],
            enable: data[i].enable,
            keyStr: data[i].keyStr,
            level: data[i].level,
            name: data[i].name,
            type: data[i].type,
            _id: data[i]._id,
            status: false,
            flag: false,
            stopSave: false
          }
          this.tableData.push(obj)
          if (data[i].child) {
            this.handleLabel(data[i].child)
          }
        }
      }
    },
    components: {
      callLabelTree
    },
    beforeMount () {
    },
    mounted () {
      this.fetchData()
    }
  }
</script>
<style lang="stylus" scoped>
  @import "../../../../../assets/common.styl"
  .state
    margin-left: 20px
  .call-label
    overflow-y: auto
    height: calc(100vh - 173px)
    .title
      color $c-prompt
      height 30px
      line-height 30px
      padding 3px 10px
      overflow hidden
      text-overflow ellipsis
      max-width 100%
      white-space nowrap
      cursor pointer
    .operate-div
      display flex
      align-items center
      height 30px
      padding 10px 10px 5px
      border 1px solid #E7E7EB
      border-bottom none
      .left
        /*float left*/
        /*padding-top 5px*/
        .add
          padding-right 10px
          cursor pointer
      .right
        width 190px
        /*float left*/
        margin-left 20px
      .el-icon-plus,.icon-shuaxin,.icon-daoru,.icon-daochu1
        color $c-main
        font-size 14px
        margin-right 2px
    .pull-right
      float right
    .btn-wrap
      padding-bottom 10px
      overflow hidden
      .temp-download
        float left
        a
         color #fff
      .temp-upload
       float left
       display inline-block
       margin-left 20px
      .temp-upload-btn
        font-size 12px
        padding 8px 15px
</style>
<style lang='stylus'>
  .operate-div
   .el-input__icon
     line-height 0px
</style>



















